#! /bin/sh
## 服务端自动化编译部署脚本 .Power by terrfly

#引入config
. ./config.sh

##  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  环境变量参数设置  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
##  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  环境变量参数设置  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑


##  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  函数定义  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓


##设置setIsInstall
function setIsInstall()
{
	local param=$1
	if [[ "$param" == "--install" ]];then
		isInstall=1
	fi
}


##备份项目并发布
function installWebProject()
{

	local subAppName=$1
	local subAppRealName="${webProjectMap[$subAppName]}"
	
	#进入源码目录下
	cd $webProjectResourcePath/$subAppRealName
	
	#更新代码
	git pull
	
	#构建项目
	local npmResult=`npm run build | grep "Build complete."`
	
	##当构建出现异常，直接退出shell
	if [ "$npmResult" == "" ];then
		echo "[$subAppRealName] ERROR: npm build error !  exit 0 !!!!"
		exit 0
	fi
	
	##当isInstall != 1 说明无需安装
	if [ $isInstall != 1 ];then
		return 1
	fi
	
	
	##安装目录是否存在， 不存在则创建
	if [ ! -d $webProjectInstallPath/$subAppRealName ]; then 
		  mkdir $webProjectInstallPath/$subAppRealName
	fi

	# 进入安装目录
	cd $webProjectInstallPath/$subAppRealName
	
	# TODO备份
	
	# 删除
	rm -rf ./*
	
	# 安装
	cp -r $webProjectResourcePath/$subAppRealName/dist/* .

	echo "[$subAppRealName] install success."

	#返回主目录
	cd $currentPath

}




##  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  函数定义  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

##  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  1. 检查  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

##遍历所有参数
for paramItem in $@; do
	setIsInstall $paramItem   ##获取是否安装参数
done

##如第一个参数为null 提示错误信息.
if [ ! -n "$1" ];then
	echo "ERROR: please input appName [${!webProjectMap[@]}]"
	exit 0
fi

checkWebProjectName $1 ##调用hasVal,判断项目名是否合法，并返回结果。 1-通过
##当第一个参数不等于all并且不在projects数组中
if [ $? != 1 ];then
	echo "ERROR: appName[$1] is not available!"
	exit 0
fi


##  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  1. 检查  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑


## 安装程序 ↓↓↓↓↓↓
echo ""
echo "【>>】webProject package ..."
if [ "$1" == "all"  ];then	
	for v in ${!webProjectMap[@]};do
		installWebProject "$v"
	done
else
	installWebProject "$1"
fi

echo 'Done.'
